﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebSearch.Helpers
{
    public class QueryBuilder
    {
        public enum Mode
        {
            AND,
            OR
        }

        private Mode mode;

        public QueryBuilder(Mode mode = Mode.AND)
        {
            this.mode = mode;
        }

        public String BuildQuery(String query)
        {
            List<String> parts = new List<String>();
            char[] delimiters = {'"', ' '};
            int start = 0;
            int pos = 0;
            while ((pos = query.IndexOfAny(delimiters, start)) != -1)
            {
                switch (query[pos])
                {
                    case ' ':
                        if (pos > start)
                        {
                            parts.Add(query.Substring(start, pos - start));
                        }
                        break;
                    case '"':
                        start = pos;
                        pos = query.IndexOf('"', start + 1);
                        if (pos != -1)
                        {
                            parts.Add(query.Substring(start, pos - start + 1));
                        }
                        else
                        {
                            parts.Add(query.Substring(start));
                            start = query.Length;
                        }
                        break;
                }
                start = pos + 1;
            }
            if (start < query.Length) {
                parts.Add(query.Substring(start));
            }

            return String.Join(String.Format(" {0} ", mode.ToString()), parts);
        }
    }
}